/******************************************************************************
 * @File name   :      DealerUsrGrpApprovalController.java
 *
 * @Author      :      NieShengjie
 *
 * @Date        :      2011-6-7
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-6-7 下午04:37:48        NieShengjie     1.0            Initial Version
 * 2011-6-16 下午8:26:48        HeHao     1.1            Change Method getDealerCodeListByMac
 * 2011-10-21 下午02:20:27        HeHao   1.2             Change Method getUserGroupApplicationDetail
 * 2011-12-06 下午02:20:27        caijunyi   1.3          fix rfs bug
 *****************************************************************************/
package com.cap.bts.framework.dm.approval.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;

import com.cap.bts.commonfunc.ge.dealer.domain.DealerInfo;
import com.cap.bts.commonfunc.ge.dealer.service.IDealerService;
import com.cap.bts.framework.approvalrule.constants.ApprovalCategoryConstants;
import com.cap.bts.framework.approvalrule.constants.RuleStepCode;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.CodeTextUtils;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.dm.approval.constant.PageConstants;
import com.cap.bts.framework.dm.approval.dto.ApplicationResultDto;
import com.cap.bts.framework.dm.approval.dto.ApprovalSubmitDto;
import com.cap.bts.framework.dm.approval.dto.QueryApplicationDto;
import com.cap.bts.framework.dm.approval.dto.QueryApproveDto;
import com.cap.bts.framework.dm.approval.service.IDealerUsrGrpApprovalService;
import com.cap.bts.framework.usermgnt.constant.OrganizationType;
import com.cap.bts.framework.usermgnt.constant.UserGroupCode;
import com.cap.bts.framework.usermgnt.constant.UserGroupLevel;
import com.cap.bts.framework.usermgnt.constant.UserGroupType;
import com.cap.bts.framework.usermgnt.domain.EmployeeInfo;
import com.cap.bts.framework.usermgnt.domain.Organization;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserGroup;
import com.cap.bts.framework.usermgnt.service.IEmployeeInfoService;
import com.cap.bts.framework.usermgnt.service.IOrganizationMgntService;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;
import com.cap.bts.framework.usermgnt.util.OrganizationUtil;


/**
 * dealer user group approval controller
 */
@Controller
@RequestMapping(value = "/dm/approval")
public class DealerUsrGrpApprovalController extends BaseController {

    private static final String INIT_PAGE = "initPage";
    private static final String LIST_PAGE = "list";
    private static final String DETAIL_PAGE = "detali";

    @Autowired
    private IDealerUsrGrpApprovalService dealerUsrGrpApprovalService;
    @Autowired
    private IOrganizationMgntService orgMgntService;
    @Autowired
    private IDealerService dealerFunService;
    @Autowired
    private IUserMgntService userMgntService;
    @Autowired
    private IEmployeeInfoService employeeInfoService;

    /**
     * seach application
     * @Date        :      2011-6-27
     * @param queryApplicationDto QueryApplicationDto
     * @return ModelAndView
     * @throws AppException AppException
     */
    @RequestMapping(value = "/getUserGroupApplication", method = RequestMethod.POST)
    public ModelAndView getUserGroupApplication(QueryApplicationDto queryApplicationDto)
        throws AppException {
        User user = getCurrentUser();
        queryApplicationDto.setUser(user);
        
        queryApplicationDto.setUserCode(user.getUserCode());
        queryApplicationDto.setUserGroupId(user.getUserGroup().getId());
        queryApplicationDto.setUserGroupCode(user.getUserGroup().getUserGroupCode());
        queryApplicationDto.setUserGroupName(user.getUserGroup().getUserGroupName());
        
        //UserGroup userGroup = user.getCurUserGroup();
        /*
        if(UserGroupCode.RFSCODE.getValue().equals(userGroup.getUserGroupCode())
            || UserGroupCode.SALES_VICE_MANAGER.getValue().equals(userGroup.getUserGroupCode())){
            //rfs user 
            List<Organization> rfsOrgs = orgMgntService.getOrganizationsByUserCodeAndOrgType(user.getUserCode(),OrganizationType.RFS);
            Organization rfsOrg = OrganizationUtil.getOrganizationByList(rfsOrgs);
            if(rfsOrg != null){
                queryApplicationDto.setRfsCode(rfsOrg.getOrgCode());
            }
        }*/
        Long brandId = queryApplicationDto.getBrandId();
        if (brandId == null || brandId == 0){
            brandId = user.getBrandId();
        }
        List<ApplicationResultDto> resultDto = dealerUsrGrpApprovalService
            .getUserGroupApplication(queryApplicationDto, true);
        Map<String, Object> map = new HashMap<String, Object>();
        List<Organization> rfsOrgs =  orgMgntService.getOrgByOrgType(OrganizationType.RFS, queryApplicationDto.getBrandId());
        map.put("rfsList", rfsOrgs);
        map.put("resultDtoList", resultDto);
        
        
        List<Organization> macOrgList = OrganizationUtil.getMacOrgsByCurrentUserOrgType(user);
        map.put("macOrgList", macOrgList);
        map.put(CommonConstants.REQUEST_ATTRIBUTE_PAGER, queryApplicationDto.getPager());
        map.put("queryApplicationDto", queryApplicationDto);
        List<UserGroup> normalUserGroupList = 
            userMgntService.findUserGroupByTypeAndLevel(UserGroupType.DEALER.getValue(), queryApplicationDto.getBrandId(), UserGroupLevel.NON_KEY.getValue());
        map.put("userGroupList", normalUserGroupList);
        
        //map.put("userGroupList", userMgntService.getAllUserGroups());
        map.put("dealerCodeList", getDealerCodeListByMac()); 
        String page = getReturnPage(LIST_PAGE, queryApplicationDto.getBrandId(),
            queryApplicationDto.getApprovalCategory(), user.getUserGroup().getUserGroupCode(),null);
        return new ModelAndView(page, map);
    }

   


    

    /**
     * 审批
     * @Date        :      2011-6-27
     * @param applicationId applicationId
     * @param brandId brandId
     * @return ModelAndView
     * @throws AppException AppException
     */
    @RequestMapping(value = "/getUserGroupApplicationDetail", method = RequestMethod.GET)
    public ModelAndView getUserGroupApplicationDetail(
        @RequestParam("applicationId") long applicationId, @RequestParam("brandId") long brandId)
        throws AppException {
        Map<String, Object> map = new HashMap<String, Object>();
        ApplicationResultDto appDetailDto = dealerUsrGrpApprovalService
            .getUserGroupApplicationDetail(applicationId);
        map.put("appDetailDto", appDetailDto);
        ApprovalSubmitDto submitDto = new ApprovalSubmitDto();
        map.put("brandId", brandId);
        map.put("transferData", false);
        QueryApplicationDto queryApplicationDto = setUserGroupAndBrandIdForQueryApplicationDto(null);
        EmployeeInfo oldEmpInfo =employeeInfoService.getEmployeeInfoByCertificate(appDetailDto.getCertificateId(), appDetailDto.getCertificateNo());
            if(appDetailDto.getOperationType().equals(CodeTextUtils.getText("UserGroupApplication.OperationType",String.valueOf(1)))){
                if(oldEmpInfo!=null){
                    submitDto.setOldEmpUserCode(oldEmpInfo.getUserCode());
                    submitDto.setNewEmpUserCode(appDetailDto.getUserCode());
                    map.put("transferData", true);
                }
            }
        map.put("approvalResultList", CodeTextUtils.getStatusMap("Approval.Result"));
        String page = getReturnPage(DETAIL_PAGE, brandId, appDetailDto.getApprovalCatgory(),
            queryApplicationDto.getUserGroupCode(),submitDto);
        map.put("submitDto", submitDto);
        return new ModelAndView(page, map);
    }

    /**
     * approval
     * 
     * @Date : 2011-6-14
     * @param submitDto
     *            submitDto
     * @return ModelAndView
     * @throws AppException
     *             AppException
     */
    @RequestMapping(value = "/approveUserGroupApplication", method = RequestMethod.POST)
    public ModelAndView approveUserGroupApplication(ApprovalSubmitDto submitDto,
        HttpServletRequest request) throws AppException {
        User user = (User) request.getSession().getAttribute("userSession");
        submitDto.setLoginId(user.getId());
        UserGroup usrGrp = user.getUserGroup();
        submitDto.setUserGroupId(usrGrp.getId());
        
        dealerUsrGrpApprovalService.approveUserGroupApplication(submitDto);
        QueryApplicationDto queryApplicationDto = new QueryApplicationDto();
        queryApplicationDto.setBrandId(new Long(submitDto.getBrandId()));
        queryApplicationDto.setApprovalCategory(submitDto.getApprovalCategory());
        queryApplicationDto.setUserGroupCode(user.getUserGroup().getUserGroupCode());
        queryApplicationDto.setRuleStep(submitDto.getStepCode());
        return getUserGroupApplication(queryApplicationDto);
    }


    /**
     * 审批关键岗位
     * 
     * @Date : 2011-6-7
     * @return ModelAndView
     * @throws AppException
     */
    @RequestMapping(value = "/toMacApproveKeyUsrGrpPage", method = RequestMethod.GET)
    public ModelAndView getMacApproveKeyUsrGrpPage() throws AppException {
		User user = (User) RequestContextHolder.currentRequestAttributes()
				.getAttribute("userSession", RequestAttributes.SCOPE_SESSION);
		UserGroup usrGrp = user.getUserGroup();

		Map<String, Object> map = new HashMap<String, Object>();// //
		QueryApplicationDto queryApplicationDto = setUserGroupAndBrandIdForQueryApplicationDto(null);
		if (usrGrp != null
				&& usrGrp.getUserGroupCode().equals(
						UserGroupCode.RFSCODE.getValue())) {
			queryApplicationDto.setRuleStep(RuleStepCode.RFSToKeyPosition
					.name());
		} else if (usrGrp != null
				&& usrGrp.getUserGroupCode().equals(
						UserGroupCode.MACCODE.getValue())) {
			queryApplicationDto.setRuleStep(RuleStepCode.MACToKeyPosition
					.name());
		}
		queryApplicationDto
				.setApprovalCategory(ApprovalCategoryConstants.KEY_STATION);
		map.put(INIT_PAGE, true);
		map.put("queryApplicationDto", queryApplicationDto);
		map.put("dealerCodeList", getDealerCodeListByMac());
		return new ModelAndView("/dm/approval/search_dms_key_usrgrp_application", map);
    }

    /**
     * get page of mac approve normal user group
     * 
     * @Date : 2011-6-7
     * @return ModelAndView
     * @throws AppException
     *             the appException
     */
    @RequestMapping(value = "/toMacApproveNormalUserPage", method = RequestMethod.GET)
    public ModelAndView getMacApproveNormalUserPage() throws AppException {
        Map<String, Object> map = new HashMap<String, Object>();
        QueryApplicationDto queryApplicationDto = setUserGroupAndBrandIdForQueryApplicationDto(null);
        queryApplicationDto.setApprovalCategory(ApprovalCategoryConstants.NORMAL_STATION);
        
        long brandId = queryApplicationDto.getBrandId();
        List<UserGroup> normalUserGroupList = 
            userMgntService.findUserGroupByTypeAndLevel(UserGroupType.DEALER.getValue(), brandId, UserGroupLevel.NON_KEY.getValue());
        map.put("userGroupList", normalUserGroupList);
        
        String page = null;
        queryApplicationDto.setRuleStep(RuleStepCode.MACToNormalPosition.name());
        page = "/dm/approval/search_dms_mac_normal_usrgrp_application";
        map.put(INIT_PAGE, true);
        map.put("queryApplicationDto", queryApplicationDto);
        map.put("dealerCodeList", getDealerCodeListByMac());
        return new ModelAndView(page, map);
    }

    /**
     * set user group and brand id for query application date transfer data
     * object
     * 
     * @Date : 2011-6-7
     * @return the queryApplicationDto
     */
    private QueryApplicationDto setUserGroupAndBrandIdForQueryApplicationDto(
        QueryApplicationDto queryApplicationDto) {
        if (queryApplicationDto == null) {
            queryApplicationDto = new QueryApplicationDto();
        }
        User user = (User) RequestContextHolder.currentRequestAttributes().getAttribute(
            "userSession", RequestAttributes.SCOPE_SESSION);
        UserGroup usrGrp = user.getUserGroup();
        queryApplicationDto.setBrandId(user.getBrandId());
        queryApplicationDto.setUserGroupId(usrGrp.getId());
        queryApplicationDto.setUserGroupCode(usrGrp.getUserGroupCode());
        queryApplicationDto.setUserCode(user.getUserCode());
        return queryApplicationDto;
    }
    
   

    /**
     * get return page
     * 
     * @Date : 2011-6-10
     * @param brandId
     *            brand
     * @param approveCategory
     *            category
     * @param userGroupCode
     *            login group code
     * @return page
     */
    private String getReturnPage(String type, long brandId, int approveCategory,
        String userGroupCode,ApprovalSubmitDto submitDto) {
        String ruleStep="";
        String page=PageConstants.APPROVAL_NOT_FIND;
        if(approveCategory == ApprovalCategoryConstants.KEY_STATION){//key group
            if (userGroupCode.equals(UserGroupCode.MACCODE.getValue())){//mac
                if( type.equals(LIST_PAGE)){//list
                    page=  PageConstants.MAC_KEY_GROUP_LIST;
                }else if( type.equals(DETAIL_PAGE)){//detail
                    ruleStep=RuleStepCode.MACToKeyPosition.name();
                    page=  PageConstants.MAC_KEY_GROUP_DETAIL;
                }
            }else if(userGroupCode.equals(UserGroupCode.RFSCODE.getValue())){
            	if( type.equals(LIST_PAGE)){//list
                    page=  PageConstants.MAC_KEY_GROUP_LIST;
                }else if(type.equals(DETAIL_PAGE)){//detail
                    ruleStep=RuleStepCode.RFSToKeyPosition.name();
                    page=  PageConstants.MAC_KEY_GROUP_DETAIL;
                }
            }
        }else if(approveCategory == ApprovalCategoryConstants.NORMAL_STATION){//normal group
            if (userGroupCode.equals(UserGroupCode.MACCODE.getValue())){//mac
                if(type.equals(LIST_PAGE)){//bui,list//brandId==BrandConstants.BUI && 
                        ruleStep = RuleStepCode.MACToNormalPosition.name();
                        page=  PageConstants.MAC_NORMAL_GROUP_LIST;
                }else if( type.equals(DETAIL_PAGE)){//bui,detail//brandId==BrandConstants.BUI &&
                        ruleStep=RuleStepCode.MACToNormalPosition.name();
                        page=  PageConstants.MAC_NORMAL_GROUP_DETAIL;
                }
            }
        }
        if(submitDto!=null){
            submitDto.setStepCode(ruleStep);
        }
        return page;
    }
    /**
     * mac获取经销商代码列衿
     * @Date        :      Dec 6, 2011
     * @return
     * @throws AppException
     */
    private List<String> getDealerCodeListByMac() throws AppException {
        User user = this.getCurrentUser();
        List<Organization> orgList = orgMgntService.getOrganizationsByUserCode(user.getUserCode());
        DealerInfo dealerInfo;
        List<String> dealerCodeList = new ArrayList<String>();
        List<Organization> dealerOrgList = new ArrayList<Organization>();
        for (Organization org : orgList) {
            if (org.getOrgType() == OrganizationType.MAC) {
                dealerOrgList = orgMgntService.getDealersBySGMOrgId(org.getId());
                for (Organization dealerOrg : dealerOrgList) {
                    if(Utils.notNullAndZero(dealerOrg.getId())){
                        dealerInfo = dealerFunService.getDealerByDealerOrgId(dealerOrg.getId());
                        if(dealerInfo!=null){
                            dealerCodeList.add(dealerInfo.getDealerCode());
                        }
                    }
                }
            }
        }
        return dealerCodeList;
    }
    

    /**
     * 
     * @Date : 2012-7-26
     * @return ModelAndView
     * @throws AppException 
     */
    @RequestMapping(value = "/getUserGroupApprove", method = RequestMethod.POST)
    public ModelAndView getUserGroupApprove(QueryApproveDto queryApproveDto ) throws AppException {
    	Map<String, Object> map = new HashMap<String, Object>();
        User user = this.getCurrentUser();
        queryApproveDto.setUser(user);
       // List<ApprovalResultDto> resultDto = userApprovalRuleService.getApproveResultByPageCondition(queryApproveDto);
        List<Organization> listOrg = OrganizationUtil.getRfsOrgsByCurrentUserOrgType(user);
        if(listOrg!=null && listOrg.size()>1){
        	map.put("length", 2);
        }else if(listOrg!=null && listOrg.size()==1){
        	map.put("length", 1);
        }
      //  map.put("resultDtoList", resultDto);
        map.put("rfsList", listOrg);
        map.put("queryApproveDto", queryApproveDto);
        map.put(CommonConstants.REQUEST_ATTRIBUTE_PAGER, queryApproveDto.getPager());
        return new ModelAndView(PageConstants.QUERY_APPROVAL_LIST, map);
    
    }
    
    /**
     * 
     * @Date : 2012-7-26
     * @return ModelAndView
     * @throws AppException 
     */
    @RequestMapping(value = "/getUserGroupApproveDetail", method = RequestMethod.GET)
    public ModelAndView getUserGroupApproveDetail(@RequestParam("applicationId") long applicationId, @RequestParam("brandId") long brandId) throws AppException {
    	Map<String, Object> map = new HashMap<String, Object>();
        ApplicationResultDto appDetailDto = dealerUsrGrpApprovalService.getUserGroupApplicationDetail(applicationId);
        map.put("appDetailDto", appDetailDto);
        return new ModelAndView(PageConstants.QUERY_APPROVAL_DETAIL, map);
    
    }
    
   
}
